package com.heima.aop;

import com.heima.annotation.AutoFill;
import com.heima.constant.AutoFillConstant;
import com.heima.enums.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class AutoFillAspect {

    /**
     * 在带有 @AutoFill 注解的方法执行之前执行
     * 插入和更新操作，对公共字段进行填充
     */
    @Before("@annotation(autoFill)")
    public void autoFillBefore(JoinPoint joinPoint, AutoFill autoFill) {
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) return;

        for (Object arg : args) {
            if (arg instanceof Iterable<?>) {
                for (Object entity : (Iterable<?>) arg) {
                    fillEntity(entity, autoFill);
                }
            } else {
                fillEntity(arg, autoFill);
            }
        }
    }

    // 抽取公共填充方法，避免代码重复
    private void fillEntity(Object entity, AutoFill autoFill) {
        LocalDateTime now = LocalDateTime.now();

        try {
            if (autoFill.value() == OperationType.INSERT) {
                Method setCreateTime = entity.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = entity.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);

                setCreateTime.invoke(entity, now);
                setUpdateTime.invoke(entity, now);

            } else if (autoFill.value() == OperationType.UPDATE) {
                Method setUpdateTime = entity.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                setUpdateTime.invoke(entity, now);
            }
        } catch (NoSuchMethodException e) {
            // 该实体没有某些set方法，忽略或打印日志
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}